// 一  udp服务器
const config = require("../config/config");
const udpDbModel = require("../model/updDbModel");

//负责聊天socket.io事件 绑定处理模块
const chatServer = require("./chatServer");
// const getCookie = require("../utils/cookie");

//导入操作client的数据模型
const clientModel = require("../model/chatClientModel");

// 2.UDP服务构建及监听
var dgram = require("dgram");
var server = dgram.createSocket("udp4");
const clientSocket = dgram.createSocket("udp4");

// 绑定udp端口
server.bind(config.udpPort);
// udp服务关闭
server.on("close", () => {
    console.log("socket已关闭");
});

// udp服务器错误
server.on("error", (err) => {
    console.log("udp服务错误", err);
});

// 启动udp监听服务
server.on("listening", () => {
    var address = server.address();
    console.log(
        "UDP server listening in " + address.address + ":" + address.port
    );

    // 3.socket服务启动后端服务 待客户端连接触发
    chatServer.on("connection", (socket) => {
        // console.log("UDP_socket:", socket);

        let json = {
            data: { msg: "后端服务器启动成功，收到客户端连接请求！" },
            from: "uid",
            sid: "sid",
            kf: "null",
            nick: "server_nick " || "小萝莉x",
            time: new Date().getTime(),
        };
        socket.emit("clinet-frist-push", json);

        socket.on("disconnect", (res) => {
            // serverModel.updateServerStatus(uid, socket.id).then((res) => { console.log('更新客服离线名单', res.insertId); });
            console.log("离线了", res);
        });

        socket.on("user-message", (msg) => {
            //返回的数据变量不能加括号 否则msg没有数据
            console.log("收到客户端信息：", msg);
            let hex16 = Bytes2HexString(msg.content);
            // console.log("收到数据转16进制：", hex16)

            //发送UDP数据给UDP客户端
            // console.log("udpclinet：",udpClientPort,updClientIP)
            //监听指定地址以及端口
            //第一个参数是发送数据，第二个参是位端口号，第三个参数为ip地址
            // clientSocket.send(msg.content, udpClientPort || 7000, updClientIP || "192.168.0.100")
            let str16 = Hexstring2btye(msg.content)
            let strs = msg.content.split(" "); //将一个十六进制报文转为字符数组
            console.log("16-hex:", str16, "strs:", strs)

            let buffer = Buffer.from(strs); //将数组放到buffer
            // let hex163 = new Buffer(strs, 'base64').toString('hex');
            // clientSocket.send(str16, udpClientPort, updClientIP); //发送buffer
            clientSocket.send(strs, udpClientPort, updClientIP, function (
                err,
                bytes
            ) {
                if (err) {
                    console.log("udp发送错误：", err);
                }
            });

            console.log(
                "发送到设备UPD客户端：", "\n",
                msg.content, "\n",
                // buffer16, "\n",
                buffer, "\n",
                // hex163, "\n",
                str16, "\n",
                udpClientPort, "\n",
                updClientIP
            );
        });

        // 2.UDP服务构建及监听消息事件
        let updClientIP;
        let udpClientPort;
        // 握手指令
        str = "46 49 4E 53 00 00 00 0C 00 00 00 00 00 00 00 00 00 00 00 6B"
        strs = str.split(" ");//将一个十六进制报文转为字符数组
        for (let i = 0; i < strs.length; i++) {
            strs[i] = "0x" + strs[i];
        }//每个字符加上0x
        let buffer = Buffer.from(strs);//将数组放到buffer


        // 读取指令
        str1 = "46 49 4E 53 00 00 00 1A 00 00 00 02 00 00 00 00 80 00 02 00 01 00 00 6B 00 00 01 01 B1 00 64 00 00 0A"
        strs1 = str1.split(" ");//将一个十六进制报文转为字符数组
        for (let i = 0; i < strs1.length; i++) {
            strs1[i] = "0x" + strs1[i];
        }//每个字符加上0x
        let buffer1 = Buffer.from(strs1);//将数组放到buffer

        server.on("message", (msg, rinfo) => {
            const buf = Buffer.from(msg);
            console.log("objData1:", buf.toString("hex"));
            var rfidData = `${msg}`;
            // console.log("msg:", msg)
            // console.log( `receive message from ${rinfo.address}:${rinfo.port} msg:${msg}`);
            // 获取客户端地址来访
            updClientIP = rinfo.address;
            udpClientPort = rinfo.port;
            server.send(buffer, rinfo.port, rinfo.address)
            socket.emit("server-message-push", rfidData);
        });


    });
});




// 二 建立tcp socket服务
const net = require('net');
const client = new net.Socket();
// const config=require('../config/config')
// const DB=require('../db/db')
const OPTION = config;

// 握手指令
str = "46 49 4E 53 00 00 00 0C 00 00 00 00 00 00 00 00 00 00 00 6B";
strs = str.split(" ");//将一个十六进制报文转为字符数组
for (let i = 0; i < strs.length; i++) {
    strs[i] = "0x" + strs[i];
}//每个字符加上0x
let buffer = Buffer.from(strs);//将数组放到buffer


// 读取/当前产量指令
str1 = "46 49 4E 53 00 00 00 1A 00 00 00 02 00 00 00 00 80 00 02 00 00 00 00 00 00 DA 01 01 82 38 70 00 00 18";
strs1 = str1.split(" ");//将一个十六进制报文转为字符数组
for (let i = 0; i < strs1.length; i++) {
    strs1[i] = "0x" + strs1[i];
}//每个字符加上0x
let buffer1 = Buffer.from(strs1);//将数组放到buffer



client.setTimeout(OPTION.timeout);
client.setEncoding(OPTION.encoding);


client.on('end', () => {
    console.log('Client disnected');
});

client.on('close', () => {
    console.log('tcp connection closed');
    reConnect()
});

client.on('error', err => {
    console.log("tcp错误",err);
});
client.on('timeout', (res) => {
    console.log("tcp超时",res);
});

var DBTable="dayyeild";
function conncect() {
    client.connect(OPTION.tcpOption, () => {
        OPTION.retriedTimes = 0;
        // infoLogger.info
        console.log(`tcp conncet success!--->local:${client.localAddress}:${client.localPort}=>remote:${client.remoteAddress}:${client.remotePort}`);
        client.write(buffer);//服务器向客户端发送握手消息
        setTimeout(sendReader, 1000)
        function sendReader(){
            DBTable="nightyeild"
            client.write(buffer1);
            
        }

    });
}

//导入操作server的数据模型
// const Db = require("../db/db");
const { table } = require("console");
client.on('data', data => 
  {
    // const buf = Buffer.alloc(100);
    const buf= Buffer.from(data);
    console.log("objData1:", buf);
    let hex16 = buf.toString("hex")
    console.log('Res_DATA: ' + data);
    console.log("hex16:", hex16)
    // client.write(buffer);//服务器向客户端发送消息
    // client.destroy();// close connect
    // var ArrHex16 = hex16.split("")
    // console.log("te", ArrHex16)





});

// 处理产量信息保存

var dayAddress = "date,H0809,H0910,H1011,H1112,H1213,H1314,H1415,H1516,H1617,H1718,H1819,H1920,allh";
var nightAddress = "date,H2021,H2122,H2223,H2324,H2401,H0102,H0203,H0304,H0405,H0506,H0607,H0708,allh"
var JsonData = ["2021-09-13", 5555, 3343, 1011, 233, 333, 1314, 1415, 1516, 1617, 1718, 1819, 1920, 666]

// console.log(DBTable, dayAddress, JsonData)
// Db.ld_z2(DBTable, dayAddress, JsonData)
// Db.WriteDayYeild()



//Reconnect server
function reConnect() {
    if (OPTION.retriedTimes >= OPTION.maxReTries) {
        console.log('Max retries have been exceeded,I give up.');
    } else {
        OPTION.retriedTimes += 1;
        console.log(`connect:${OPTION.retriedTimes}`);
        setTimeout(conncect, OPTION.retryInterval);
    }
}

// conncect();
module.exports = client